<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 充电桩管理界面
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <div class="handle-box-left">
          <el-input style="width: 60%" v-model="queryInfo.chargePileId" placeholder="请输入充电桩ID" class="handle-input mr10"></el-input>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button @click="getPileList">重置</el-button>
        </div>
        <div class="handle-box-right">
          <el-button type="primary" icon="el-icon-plus" @click="addVisible = true" round>新增</el-button>
          <!-- 弹出新增框 -->
          <el-dialog title="新增充电桩" v-model="addVisible" width="30%">
            <el-form ref="addFormRef" :model="addForm" label-width="100px">
              <el-form-item label="充电功率">
                <el-input v-model="addForm.chargePower"></el-input>
              </el-form-item>
              <el-form-item label="纬度">
                <el-input v-model="addForm.latitude"></el-input>
              </el-form-item>
              <el-form-item label="经度">
                <el-input v-model="addForm.longitude"></el-input>
              </el-form-item>
              <el-form-item label="充电方式">
                <el-radio v-model="addForm.dc" label="1">直流</el-radio>
                <el-radio v-model="addForm.dc" label="2">交流</el-radio>
              </el-form-item>
              <el-form-item label="充电速度">
                <el-radio v-model="addForm.fast" label="1">快充</el-radio>
                <el-radio v-model="addForm.fast" label="2">慢充</el-radio>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveadd">确 定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </div>

      <el-table :data="Pilelist" @sort-change="SortChange" @filter-change="filterChange" border class="table" ref="multipleTable" header-cell-class-name="table-header" stripe>
        <el-table-column prop="chargePileId" label="ID" width="70%" sortable="custom" align="center">
          <template #default="scope">{{ scope.row.chargePileId }}</template>
        </el-table-column>

        <el-table-column prop="chargePower" label="充电功率" sortable="custom" align="center">
          <template #default="scope">{{scope.row.chargePower}}</template>
        </el-table-column>
        <el-table-column prop="chargeHours" label="总充电时间" sortable="custom" align="center"><template #default="scope">{{
            scope.row.chargeHours
          }}</template></el-table-column>
        <el-table-column label="充电桩位置" align="center">
          <template #default="scope">
            <p>纬度：{{ scope.row.latitude }}</p>
            <p>经度：{{ scope.row.longitude }}</p>
          </template>
        </el-table-column>
        <el-table-column :filters="[
            { text: '已激活', value: 'active' },
            { text: '未激活', value: 'inactive' },
            { text: '故障', value: 'error' },
          ]" column-key="filterTag" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.error ? 'danger':(scope.row.active ?'primary':'info')">
              {{ scope.row.error ? "故障": (scope.row.active ? "已激活" : "未激活")}}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="安装时间" align="center">
          <template #default="scope">{{ scope.row.installDate }}</template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="flex flex-wrap items-center">
              <el-dropdown>
                <el-button type="primary">
                  操作<el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleEdit(scope.$index, scope.row)">修改</el-dropdown-item>
                    <el-dropdown-item @click="handleActive(scope.$index, scope.row)">激活</el-dropdown-item>
                    <el-dropdown-item @click="handleShutDown(scope.$index, scope.row)">关停</el-dropdown-item>
                    <el-dropdown-item @click="handleSetError(scope.$index, scope.row)">设置为故障</el-dropdown-item>
                    <el-dropdown-item @click="handleRecovery(scope.$index, scope.row)">从故障中恢复</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
                <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">
                  删除
                </el-button>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="pageIndex" :page-size="pageSize" :total="totalElements" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="修改充电桩属性" v-model="editVisible" width="30%">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="充电功率">
          <el-input v-model="editForm.chargePower"></el-input>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="editForm.latitude"></el-input>
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="editForm.longitude"></el-input>
        </el-form-item>
        <el-form-item label="充电方式">
          <el-radio v-model="editForm.dc" label="1">直流</el-radio>
          <el-radio v-model="editForm.dc" label="2">交流</el-radio>
        </el-form-item>
        <el-form-item label="充电速度">
          <el-radio v-model="editForm.fast" label="1">快充</el-radio>
          <el-radio v-model="editForm.fast" label="2">慢充</el-radio>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "basetable",
  data() {
    return {
      // 查询参数对象
      queryInfo: {
        chargePileId: null,
        orderBy: "chargePileId",
        page: 1,
        pageSize: 5,
        asc: true,
        active: true,
        error: false,
      },
      addForm: {
        chargePower: "",
        latitude: "",
        longitude: "",
        dc: "",
        fast: "",
      },
      sortItem: [
        {
          value: "chargePileId",
          label: "充电桩ID",
        },
        {
          value: "chargePower",
          label: "充电桩功率",
        },
        {
          value: "chargeHours",
          label: "总充电时间",
        },
        {
          value: "installDate",
          label: "安装时间",
        },
      ],
      editForm: {
        PileID: 1,
        chargePower: "",
        latitude: "",
        longitude: "",
        dc: "",
        fast: "",
      },
      // 商品列表
      Pilelist: [],
      // 总数据条数
      totalElements: 0,
      // 当前页
      pageIndex: 1,
      // 页大小
      pageSize: 0,
      // 总页数
      pageTotal: 0,
      // 新增框的显示
      addVisible: false,
      // 编辑框的显示
      editVisible: false,
      changeItem: null,
      newValue: null,
      successCount: 0,
    };
  },
  created() {
    this.getPileList();
  },
  methods: {
    // 根据分页获取对应的商品列表
    async getPileList() {
      const {
        totalPages: pageTotal,
        totalElements: totalElements,
        content: Pilelist,
        size: pageSize,
        number: pageIndex,
      } = await this.$axios.get(
        `pile/admin/${this.queryInfo.orderBy}/${this.queryInfo.page}/${this.queryInfo.pageSize}/${this.queryInfo.asc}`
      );
      this.totalElements = totalElements;
      this.pageTotal = pageTotal;
      this.pageSize = pageSize;
      this.pageIndex = pageIndex + 1;
      this.Pilelist = Pilelist;
      // console.log(this.Pilelist);
    },
    async getPileListByActive() {
      const {
        totalPages: pageTotal,
        totalElements: totalElements,
        content: Pilelist,
        size: pageSize,
        number: pageIndex,
      } = await this.$axios.get(
        `pile/admin/ac/${this.queryInfo.active}/${this.queryInfo.orderBy}/${this.queryInfo.page}/${this.queryInfo.pageSize}/${this.queryInfo.asc}`
      );
      this.totalElements = totalElements;
      this.pageTotal = pageTotal;
      this.pageSize = pageSize;
      this.pageIndex = pageIndex + 1;
      this.Pilelist = Pilelist;
    },
    async getPileListByError() {
      const {
        totalPages: pageTotal,
        totalElements: totalElements,
        content: Pilelist,
        size: pageSize,
        number: pageIndex,
      } = await this.$axios.get(
        `pile/admin/er/${this.queryInfo.error}/${this.queryInfo.orderBy}/${this.queryInfo.page}/${this.queryInfo.pageSize}/${this.queryInfo.asc}`
      );
      this.totalElements = totalElements;
      this.pageTotal = pageTotal;
      this.pageSize = pageSize;
      this.pageIndex = pageIndex + 1;
      this.Pilelist = Pilelist;
    },
    saveadd() {
      this.addForm.dc = this.addForm.dc == "1" ? true : false;
      this.addForm.fast = this.addForm.fast == "1" ? true : false;
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { message: res } = await this.$axios.post(
          "pile/admin",
          this.addForm
        );
        if (res !== "新增充电桩成功") return this.$message.error("新增失败");
        this.$message.success("新增成功");
        this.addVisible = false;
        this.getPileList();
      });
    },
    handlePageChange(newPage) {
      this.queryInfo.page = newPage;
      this.getPileList();
    },
    handleShutDown(index, row) {
      this.$confirm("将关停该充电桩, 是否确定?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.put(
            `pile/admin/shutOff/${row.chargePileId}`
          );
          if (res.message != "移除队列成功")
            return this.$message.error("关停失败");
          this.$message.success("成功关停该充电桩");
          this.getPileList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    handleActive(index, row) {
      this.$confirm("将激活该充电桩, 是否确定?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.put(
            `pile/admin/activate/${row.chargePileId}`
          );
          if (res.message != "新增队列成功")
            return this.$message.error("激活失败");
          this.$message.success("成功激活该充电桩");
          this.getPileList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    handleDelete(index, row) {
      this.$confirm("将删除该充电桩, 是否确定?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.delete(
            `pile/admin/${row.chargePileId}`
          );
          if (res.message != "删除充电桩成功")
            return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getPileList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSetError(index, row) {
      this.$confirm("将此充电桩设置为故障, 是否确定?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.put(
            `/pile/admin/error/${row.chargePileId}`
          );
          if (res.message != "设置充电桩故障成功")
            return this.$message.error("操作失败！");
          this.$message.success("成功将此充电桩设置为故障！");
          this.getPileList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    handleRecovery(index, row) {
      this.$confirm("将此充电桩从故障中恢复, 是否确定?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.put(
            `/pile/admin/recovery/${row.chargePileId}`
          );
          if (res.message != "修复充电桩故障成功")
            return this.$message.error("恢复失败");
          this.$message.success("恢复成功");
          this.getPileList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    async handleSearch() {
      this.Pilelist = [];
      await this.$axios
        .get(`pile/admin/${this.queryInfo.chargePileId}`)
        .then((res) => {
          this.Pilelist[0] = res;
          if (res === "") this.Pilelist = [];
          let len = this.Pilelist.length;
          this.totalElements = len;
          this.pageTotal = len;
          this.pageSize = len;
          this.pageIndex = len;
        });
    },
    handleEdit(index, row) {
      this.editVisible = true;
      this.editForm.PileID = row.chargePileId;
      const editIndex = this.Pilelist.findIndex(
        (e) => e.chargePileId == this.editForm.PileID
      );
      this.editForm.chargePower = this.Pilelist[editIndex].chargePower;
      this.editForm.latitude = this.Pilelist[editIndex].latitude;
      this.editForm.longitude = this.Pilelist[editIndex].longitude;
      this.editForm.dc = this.Pilelist[editIndex].dc ? "1" : "2";
      this.editForm.fast = this.Pilelist[editIndex].fast ? "1" : "2";
    },
    async saveEdit() {
      const res1 = await this.$axios.put(
        `pile/admin/setting/${this.editForm.PileID}/chargePower/${this.editForm.chargePower}`
      );
      if (res1.message == "充电桩信息更改成功") this.successCount++;
      const res2 = await this.$axios.put(
        `pile/admin/setting/${this.editForm.PileID}/latitude/${this.editForm.latitude}`
      );
      if (res2.message == "充电桩信息更改成功") this.successCount++;
      const res3 = await this.$axios.put(
        `pile/admin/setting/${this.editForm.PileID}/longitude/${this.editForm.longitude}`
      );
      if (res3.message == "充电桩信息更改成功") this.successCount++;
      const res4 = await this.$axios.put(
        `pile/admin/setting/${this.editForm.PileID}/dc/${
          this.editForm.dc == "1" ? true : false
        }`
      );
      if (res4.message == "充电桩信息更改成功") this.successCount++;
      const res5 = await this.$axios.put(
        `pile/admin/setting/${this.editForm.PileID}/fast/${
          this.editForm.fast == "1" ? true : false
        }`
      );
      if (res5.message == "充电桩信息更改成功") this.successCount++;
      if (this.successCount < 5) {
        this.$message.error("修改出现错误！");
      } else {
        this.$message.success("修改成功！");
      }
      this.editVisible = false;
      this.getPileList();
    },
    SortChange(column) {
      if (column.prop === null) return;
      this.queryInfo.asc = column.order === "ascending" ? true : false;
      this.queryInfo.orderBy = column.prop;
      this.getPileList();
    },
    filterChange(filters) {
      var array = Object.values(filters.filterTag);
      if (array.length == 3) return this.getPileList();
      if (array.some((e) => e == "error")) {
        // 筛选故障充电桩
        this.queryInfo.error = true;
        this.getPileListByError();
      } else if (
        array.some((e) => e == "active") &&
        array.some((e) => e == "inactive")
      ) {
        // 筛选非故障充电桩
        this.queryInfo.error = false;
        this.getPileListByError();
      } else {
        // 筛选激活、未激活的充电桩
        this.queryInfo.active = array[0] == "active" ? true : false;
        this.getPileListByActive();
      }
    },
  },
};
</script>

<style scoped>
.handle-box {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.handle-box-left {
  width: 100%;
}
.handle-select {
  width: 120px;
}

.handle-input {
  width: 15% !important;
  /* display: inline-block; */
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
